<template>
    <!-- 用户管理页面根容器 -->
    <div class="role-container">
        <!-- 页面标题区域 -->
        <div class="page-header">
            <div class="header-content">
                <h1 class="page-title">
                    <el-icon class="title-icon">
                        <UserFilled />
                    </el-icon>
                    用户管理
                </h1>
                <p class="page-description">管理系统用户信息，支持用户名查询与分页</p>
            </div>
        </div>
        <!-- 主要内容卡片 -->
        <el-card class="main-card" shadow="hover">
            <!-- 搜索区域 -->
            <div class="action-section">
                <el-form :inline="true" :model="queryInfo" class="search-form">
                    <el-form-item label="用户名" class="form-item">
                        <el-input v-model="queryInfo.UserName" placeholder="请输入用户名" clearable class="search-input"
                            @keyup.enter="handleQuery" />
                    </el-form-item>
                    <el-form-item class="form-item">
                        <el-button type="primary" @click="handleQuery" class="action-btn search-btn"
                            icon="el-icon-search">查询</el-button>
                        <el-button type="success" @click="addPopup" class="action-btn add-btn" icon="el-icon-plus"
                            style="margin-left: 12px;">用户新增</el-button>
                    </el-form-item>
                </el-form>
            </div>
            <!-- 数据表格 -->
            <div class="table-section">
                <!-- 使用v-loading指令实现加载动画 -->
                <el-table :data="userList" style="width: 100%" border class="data-table" stripe highlight-current-row
                    v-loading="loading">
                    <el-table-column prop="UserId" label="用户ID" width="150" align="center" />
                    <el-table-column prop="UserName" label="用户名" width="120" align="center" />
                    <el-table-column prop="status" label="状态" width="80" align="center">
                        <template #default="{ row }">
                            <el-tag :type="row.status ? 'success' : 'danger'">
                                {{ row.status ? '启用' : '禁用' }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="Serialnumber" label="序号" width="80" align="center" />
                    <el-table-column prop="CreateTime" label="创建时间" width="180" align="center">
                        <template #default="scope">
                            <div>
                                <!-- 使用moment.js格式化时间 -->
                                {{ moment(scope.row.CreateTime).format("YYYY-MM-DD HH:mm:ss") }}
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="RoleNames" label="角色" min-width="120" align="center" />
                    <el-table-column fixed="right" label="操作" min-width="140" align="center">
                        <template #default="scope">
                            <div class="action-buttons">
                                <el-button link type="danger" size="small" @click="deleteUser(scope.row)"
                                    class="delete-btn" icon="el-icon-delete">删除</el-button>
                                <el-button link type="primary" size="small" @click="editUser(scope.row)"
                                    class="edit-btn" icon="el-icon-edit">修改</el-button>
                            </div>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <!-- 分页组件 -->
            <div style="margin-top: 16px; display: flex; justify-content: center;">
                <div class="pagination-section">
                    <table>
                        <tr>
                            <td>
                                <el-pagination v-model:current-page="queryInfo.PageIndex"
                                    v-model:page-size="queryInfo.PageSize" :page-sizes="[5, 10, 20, 50]"
                                    layout="slot,sizes" :total="queryInfo.TotalCount" @size-change="handleSizeChange"
                                    @current-change="handleCurrentChange" prev-text="上一页" next-text="下一页">
                                    共{{ queryInfo.TotalCount }}条 每页{{ queryInfo.PageSize }}条
                                    第{{ queryInfo.PageIndex }}/{{ queryInfo.TotalPage }}页
                                </el-pagination>
                            </td>
                            <td>
                                <el-pagination v-model:current-page="queryInfo.PageIndex"
                                    v-model:page-size="queryInfo.PageSize" :page-sizes="[5, 10, 20, 50]"
                                    layout="slot,prev, pager, next" :total="queryInfo.TotalCount"
                                    @size-change="handleSizeChange" @current-change="handleCurrentChange"
                                    prev-text="上一页" next-text="下一页">
                                    <el-button @click="handleCurrentChange(1)"
                                        :disabled="queryInfo.PageIndex == 1">首页</el-button>
                                </el-pagination>
                            </td>
                            <td>
                                <el-pagination v-model:current-page="queryInfo.PageIndex"
                                    v-model:page-size="queryInfo.PageSize" :page-sizes="[5, 10, 20, 50]"
                                    layout="slot,jumper" :total="queryInfo.TotalCount" @size-change="handleSizeChange"
                                    @current-change="handleCurrentChange" prev-text="上一页" next-text="下一页">
                                    <el-button @click="handleCurrentChange(queryInfo.TotalPage)"
                                        :disabled="queryInfo.PageIndex == queryInfo.TotalPage">首页</el-button>
                                </el-pagination>
                            </td>
                        </tr>
                    </table>
                </div>

            </div>

        </el-card>

        <!-- 新增用户弹窗 -->
        <el-dialog v-model="dialogFormVisible" title="添加用户" width="600px" class="custom-dialog"
            :close-on-click-modal="false">
            <div class="dialog-content">
                <el-form :model="form" :rules="addRules" ref="addFormRef" label-width="100px" class="dialog-form">
                    <el-form-item label="用户名" prop="UserName">
                        <el-input v-model="form.UserName" placeholder="请输入用户名" clearable />
                    </el-form-item>
                    <el-form-item label="密码" prop="Password">
                        <el-input v-model="form.Password" placeholder="请输入密码" clearable show-password />
                    </el-form-item>
                    <el-form-item label="序号" prop="Serialnumber">
                        <el-input-number v-model="form.Serialnumber" :min="1" placeholder="请输入序号" style="width: 100%" />
                    </el-form-item>
                    <el-form-item label="选择角色">
                        <el-checkbox-group v-model="form.RolesId" class="role-checkbox-group">
                            <el-checkbox v-for="item in juese" :key="item.RolesId" :label="item.RolesId">
                                {{ item.RoleName }}
                            </el-checkbox>
                        </el-checkbox-group>
                    </el-form-item>
                </el-form>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogFormVisible = false" class="cancel-btn">取消</el-button>
                    <el-button type="primary" @click="addSubmit" class="confirm-btn">确认提交</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 修改用户弹窗 -->
        <el-dialog v-model="editDialogVisible" title="修改用户" width="600px" class="custom-dialog"
            :close-on-click-modal="false">
            <div class="dialog-content">
                <el-form :model="editForm" :rules="editRules" ref="editFormRef" label-width="100px" class="dialog-form">
                    <el-form-item label="用户名" prop="UserName">
                        <el-input v-model="editForm.UserName" placeholder="请输入用户名" clearable />
                    </el-form-item>
                    <el-form-item label="序号" prop="Serialnumber">
                        <el-input-number v-model="editForm.Serialnumber" :min="1" placeholder="请输入序号"
                            style="width: 100%" />
                    </el-form-item>
                    <el-form-item label="选择角色">
                        <el-checkbox-group v-model="editForm.RolesId" class="role-checkbox-group">
                            <el-checkbox v-for="item in juese" :key="item.RolesId" :label="item.RolesId">
                                {{ item.RoleName }}
                            </el-checkbox>
                        </el-checkbox-group>
                    </el-form-item>
                </el-form>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="editDialogVisible = false" class="cancel-btn">取消</el-button>
                    <el-button type="primary" @click="updateUser" class="confirm-btn">确认修改</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
// 导入所需模块和图标
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import axios from 'axios'
import { UserFilled } from '@element-plus/icons-vue'
import moment from 'moment'
import { serviceRead, serviceWrite } from '@/utils/axionrequest'

// 响应式变量定义
const userList = ref([]) // 用户列表数据
const total = ref(0)
const loading = ref(false) // 表格加载状态
// 查询条件及分页信息
const queryInfo = reactive({
    UserName: '',
    PageIndex: 1,
    PageSize: 10,
    TotalCount: 0,
    TotalPage: 0
})

// 异步方法，获取用户列表
const getUserList = async () => {
    loading.value = true // 开始加载
    try {
        const { data } = await serviceRead.get('/api/User/SraechUser', {
            params: queryInfo
        })
        if (data.code === 200) {
            userList.value = data.PageData
            queryInfo.TotalCount = data.TotalCount
            queryInfo.TotalPage = data.TotalPage
        } else {
            ElMessage.error(data.msg || '查询失败')
        }
    } catch (e) {
        ElMessage.error('请求失败')
    }
    loading.value = false // 结束加载
}

// 角色数据，用于新增和修改时选择
const juese = ref()
// 获取所有角色信息
const roleinfo = () => {
    serviceRead.get('/api/Roles/SraechRole').then(res => {
        juese.value = res.data.PageData
    })
}

// 点击查询按钮
const handleQuery = () => {
    queryInfo.PageIndex = 1 // 重置到第一页
    getUserList()
}
// 分页：每页显示条数变化
const handleSizeChange = (size: number) => {
    queryInfo.PageSize = size
    getUserList()
}
// 分页：当前页码变化
const handleCurrentChange = (page: number) => {
    queryInfo.PageIndex = page
    getUserList()
}

// 组件挂载时，初始化数据
onMounted(() => {
    roleinfo();
    getUserList();
})

// 新增用户相关
const dialogFormVisible = ref(false) // 控制新增弹窗
// 新增表单数据
const form = reactive({
    UserName: '',
    Password: '',
    Serialnumber: 1,
    RolesId: [] as number[]
})
const addFormRef = ref<FormInstance>()

const addRules = reactive<FormRules>({
    UserName: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
    Password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
    Serialnumber: [{ required: true, message: '请输入序号', trigger: 'blur' }],
})

// 打开新增弹窗并重置表单
const addPopup = () => {
    dialogFormVisible.value = true
    form.UserName = ''
    form.Password = ''
    form.Serialnumber = 1
    form.RolesId = []
}
// 提交新增用户表单
const addSubmit = async () => {
    if (!addFormRef.value) return
    await addFormRef.value.validate((valid) => {
        if (valid) {
            serviceWrite.post('/api/User/AddUserinfo', form).then(res => {
                if (res.data.code === 200) {
                    ElMessage.success(res.data.msg)
                    dialogFormVisible.value = false
                    getUserList()
                } else {
                    ElMessage.error(res.data.msg)
                }
            })
        }
    })
}

// 删除用户
const deleteUser = (row: any) => {
    ElMessageBox.confirm(
        '是否删除当前用户信息',
        '用户删除管理',
        {
            confirmButtonText: '删除',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        serviceWrite.delete('/api/User/DeleteUser', { params: { userId: row.UserId } }).then(res => {
            if (res.data.code === 200) {
                ElMessage.success(res.data.msg)
                getUserList() // 刷新列表
            } else {
                ElMessage.error(res.data.msg)
            }
        }).catch(err => {
            ElMessage.error('删除失败: ' + (err.response?.data?.msg || err.message))
        })
    }).catch(() => {
        ElMessage({
            type: 'info',
            message: '删除已取消',
        })
    })
}

// 修改用户相关
const editDialogVisible = ref(false) // 控制修改弹窗
// 修改表单数据
const editForm = reactive({
    UserId: 0,
    UserName: '',
    Password: '',
    Serialnumber: 1,
    RolesId: [] as number[]
})
const editFormRef = ref<FormInstance>()

const editRules = reactive<FormRules>({
    UserName: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
    Serialnumber: [{ required: true, message: '请输入序号', trigger: 'blur' }],
})

// 打开修改弹窗并回显数据
const editUser = (row: any) => {
    // 使用Object.assign进行浅拷贝
    Object.assign(editForm, row)
    // 反填角色，确保为数组
    if (Array.isArray(row.RolesId)) {
        editForm.RolesId = [...row.RolesId]
    } else if (Array.isArray(row.RoleNames) && juese.value) {
        // 如果后端只返回角色名，需根据角色名查找对应ID
        editForm.RolesId = juese.value.filter((j: any) => row.RoleNames.includes(j.RoleName)).map((j: any) => j.RolesId)
    } else {
        editForm.RolesId = []
    }
    editDialogVisible.value = true
}
// 提交修改用户表单
const updateUser = async () => {
    if (!editFormRef.value) return
    await editFormRef.value.validate((valid) => {
        if (valid) {
            serviceWrite.put('/api/User/UpdateUserinfo', {
                ...editForm,
                RolesId: editForm.RolesId
            }).then(res => {
                if (res.data.code === 200) {
                    ElMessage.success(res.data.msg)
                    editDialogVisible.value = false
                    getUserList()
                } else {
                    ElMessage.error(res.data.msg)
                }
            })
        }
    })
}
</script>

<style scoped>
.role-container {
    min-height: 100%;
    background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
    padding: 0;
}

.page-header {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    padding: 32px 0;
    margin-bottom: 24px;
    border-radius: 0 0 16px 16px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.header-content {
    text-align: center;
    color: white;
}

.page-title {
    font-size: 32px;
    font-weight: 600;
    margin: 0 0 8px 0;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 12px;
}

.title-icon {
    font-size: 36px;
    color: #ffd700;
}

.page-description {
    font-size: 16px;
    margin: 0;
    opacity: 0.9;
}

.main-card {
    border-radius: 16px;
    border: none;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
    backdrop-filter: blur(10px);
    background: rgba(255, 255, 255, 0.95);
}

.action-section {
    padding: 24px;
    background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
    border-radius: 12px;
    margin-bottom: 24px;
}

.search-form {
    display: flex;
    align-items: center;
    gap: 16px;
    flex-wrap: wrap;
}

.form-item {
    margin-bottom: 0;
}

.search-input {
    width: 300px;
}

.action-btn {
    border-radius: 8px;
    font-weight: 500;
    padding: 10px 20px;
    transition: all 0.3s ease;
}

.search-btn {
    background: linear-gradient(45deg, #409EFF, #67C23A);
    border: none;
}

.search-btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

.table-section {
    padding: 0 24px 24px;
}

.data-table {
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
}

.pagination-section {
    margin: 24px 0 0 0;
    text-align: right;
}

.role-checkbox-group {
    display: grid;
    grid-template-columns: repeat(2, 100px);
    gap: 30px 100px;
    justify-content: center;
}

:deep(.role-checkbox-group .el-checkbox) {
    min-width: 0;
    max-width: 180px;
    width: 100%;
}

/* 用户添加/修改弹窗 角色选择卡片美化 */
:deep(.role-checkbox-group .el-checkbox) {
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 2px 8px 0 rgba(64,158,255,0.06);
  margin-bottom: 18px;
  margin-right: 18px;
  min-width: 140px;
  min-height: 48px;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  font-size: 16px;
  padding-left: 18px;
  padding-right: 18px;
  border: 1.5px solid #e4e7ed;
  transition: all 0.2s;
}

/* 选中时高亮浅蓝色边框和阴影，字体高亮 */
:deep(.role-checkbox-group .el-checkbox.is-checked) {
  border-color: #409EFF !important;
  box-shadow: 0 2px 12px 0 rgba(64,158,255,0.12);
  color: #222 !important;
  background: #f0f7ff;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    padding-top: 20px;
}

.cancel-btn {
    border-radius: 8px;
    padding: 10px 20px;
}

.confirm-btn {
    background: linear-gradient(90deg, #409EFF 60%, #67C23A 100%);
    color: #fff;
    border: none;
    font-weight: bold;
    border-radius: 10px;
    padding: 10px 28px;
    font-size: 16px;
    box-shadow: 0 2px 8px rgba(64, 158, 255, 0.12);
    transition: background 0.2s, box-shadow 0.2s;
}

.confirm-btn:hover {
    background: linear-gradient(90deg, #66b1ff 60%, #85ce61 100%);
    box-shadow: 0 4px 16px rgba(64, 158, 255, 0.18);
}

.action-buttons {
    display: flex;
    gap: 8px;
    justify-content: center;
}

.delete-btn {
    color: #F56C6C;
    font-weight: 500;
}

.delete-btn:hover {
    background: rgba(245, 108, 108, 0.1);
    border-radius: 4px;
}

.edit-btn {
    color: #409EFF;
    font-weight: 500;
}

.edit-btn:hover {
    background: rgba(64, 158, 255, 0.1);
    border-radius: 4px;
}
</style>